package com.hcloud.auth.api.permission;

import com.hcloud.auth.api.util.AuthUtil;
import com.hcloud.common.core.base.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.stream.Stream;

/**
 * @Auther hepangui
 * @Date 2018/11/14
 */
@Slf4j
@Service("ACS")
public class AuthorityCheckService {

    public boolean has(String authority) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            return false;
        }
        User user = AuthUtil.getUser(authentication);
        //用超管帐号方便测试，拥有所有权限
        String account = user.getAccount();
        if("hepg".equals(account)){
            return true;
        }
        if(authority.contains("edit") || authority.contains("del")){
            return false;
        }
        return   AuthUtil.getAuthority().stream().anyMatch(a -> authority.equals(a));
//
//        var a = authorities.stream().takeWhile(grantedAuthority
//                -> !grantedAuthority.getAuthority().equals(authority)).count();
//        return a != authorities.size();
//
//        for (GrantedAuthority grantedAuthority : authorities) {
//            String authority1 = grantedAuthority.getAuthority();
//            if(authority1!=null && authority1.equals(authority)){
//                return true;
//            }
//        }
//        return false;
    }

}
